import 'package:shop/common/AppStorge.dart';
import 'package:shop/common/EventBus.dart';
import 'package:shop/common/shop_material.dart';
import 'package:shop/commonWidget/myFlow.dart';
import 'package:shop/commonWidget/myImage.dart';
import 'package:shop/model/memberModel/PersonalCenterResponse.dart';
import 'package:shop/utils/Storage.dart';
import 'package:shop/view/login/LoginIndex.dart';

class Page4 extends StatefulWidget {
  Page4({Key key}) : super(key: key);
  @override
  _Page4State createState() => _Page4State();
}

class _Page4State extends State<Page4> {
  PersonalCenterResponse personalCenterResponse;
  List _dingdan;
  @override
  void initState() {
    // 预加载
    Map cache = StorageUtil.getMap(MyUrl.memberpersonalCenter);
    if (cache.containsKey("Data")) {
      personalCenterResponse = PersonalCenterResponse.fromJson(cache["Data"]);
    }
    super.initState();
    _dingdan = [
      {
        "icon": "images/user/ic_wode_wait.png",
        "name": "待付款",
        "parse": "WaitPay"
      },
      {
        "icon": "images/user/ic_mine_collection.png",
        "name": "待发货",
        "parse": "WaitSend"
      },
      {
        "icon": "images/user/ic_wode_shouhuo.png",
        "name": "待收货",
        "parse": "WaitReceiving"
      },
      {
        "icon": "images/user/ic_wode_evaluate.png",
        "name": "待评价",
        "parse": "WaitEvaluate"
      },
      {
        "icon": "images/user/ic_wode_shouhou.png",
        "name": "退款售后",
        "parse": "ReturnAfterSale"
      },
    ];
    _initGetData();
    eventBus.on<UpdataUserEvent>().listen((event) {
      _initGetData();
    });
  }

  _initGetData() async {
    Map results = await MyHttp().post(MyUrl.memberpersonalCenter,
        data: {"store_id": MyStorge.storeId}, needToken: false, cache: true);
    if (this.mounted) {
      setState(() {
        personalCenterResponse = PersonalCenterResponse.fromJson(results);
        if (personalCenterResponse.memberInfo != null) {
          Map loginStorge = MyStorge.login;
          loginStorge[loginStorge["def"]]["img"] =
              personalCenterResponse.memberInfo.headerImg;
          MyStorge.login = loginStorge;
        }
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          automaticallyImplyLeading: false,
          title: Image.asset("images/user/ic_title.png", width: 204.w),
          elevation: 0,
          actions: [
            InkWell(
                onTap: () => route.pushNamed(MyRoutes.setting),
                child:
                    Image.asset("images/user/ic_me_setting.png", width: 40.w)),
            Container(
              margin: EdgeInsets.only(right: 40.w, left: 50.w),
              child: Image.asset("images/user/ic_me_message.png", width: 40.w),
            )
          ],
        ),
        body: personalCenterResponse != null
            ? Container(
                margin: EdgeInsets.only(left: 23.w, right: 18.w),
                child: ListView(
                  children: <Widget>[
                    dengLu(), //登录
                    huiYuan(), //会员
                    // 我的订单
                    cardWidget(
                        title: "我的订单",
                        subtitle: "全部订单",
                        imagePath: "images/user/ic_next.png",
                        line: 5,
                        child: _dingdan
                            .map((e) => iconWidget(
                                title: e["name"],
                                image: e["icon"],
                                count: personalCenterResponse.orderStatusTotal
                                    .toJson()[e["parse"]]))
                            .toList()),
                    kaiDian(), //免费开店
                    _getStore(), //小区店
                    _getYHQ(), //优惠券
                    cardWidget(
                        title: "常用功能",
                        line: 4,
                        padding: 10.h,
                        child: personalCenterResponse.oftenFunction
                            .map((e) => Container(
                                margin:
                                    EdgeInsets.only(bottom: 20.h, top: 20.h),
                                child:
                                    iconWidget(title: e.name, image: e.icon)))
                            .toList()),
                  ],
                ),
              )
            : Center(child: Text("加载中")));
  }

  Widget kaiDian() {
    return Container(
      margin: EdgeInsets.only(top: 20.h),
      child: MyImage.network(personalCenterResponse.style.capsulePath),
    );
  }

  Widget cardWidget(
      {String title,
      List<Widget> child,
      String subtitle = "",
      String imagePath = "",
      double padding = 21,
      int line = 1}) {
    return Container(
      margin: EdgeInsets.only(top: 20.h),
      width: 710.w,
      decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(10), color: Colors.white),
      child: Column(
        children: <Widget>[
          Container(
            padding: EdgeInsets.symmetric(horizontal: 20.w),
            height: 80.h,
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: <Widget>[
                Text("$title", style: TextStyle(fontSize: 32.s)),
                Row(children: <Widget>[
                  Text("$subtitle  ",
                      style:
                          TextStyle(color: Color(0xFF999999), fontSize: 24.s)),
                  imagePath == ""
                      ? Text("")
                      : Image.asset("$imagePath", height: 26.s)
                ])
              ],
            ),
          ),
          Divider(height: 1),
          Container(
            width: 710.w,
            padding: EdgeInsets.all(padding.w),
            child: MyFlow(line: line, children: child),
          )
        ],
      ),
    );
  }

  Widget iconWidget({String title, String image, int count = 0}) {
    return Container(
      child: Column(
        children: <Widget>[
          image.startsWith("http")
              ? MyImage.network(image, width: 60.s)
              : Container(
                  height: 60.s,
                  width: 60.s,
                  child: Stack(
                    overflow: Overflow.visible,
                    children: <Widget>[
                      Image.asset(image),
                      count > 0
                          ? Positioned(
                              left: 40.s,
                              bottom: 40.s,
                              child: ConstrainedBox(
                                constraints: BoxConstraints(minWidth: 23.s),
                                child: Container(
                                  alignment: Alignment.center,
                                  decoration: BoxDecoration(
                                      color: Colors.white,
                                      border: Border.all(
                                          color: Colors.red, width: 1),
                                      borderRadius:
                                          BorderRadius.circular(40.s)),
                                  child: Text(
                                    "$count",
                                    style: TextStyle(
                                        color: Colors.red, fontSize: 16.s),
                                  ),
                                ),
                              ),
                            )
                          : Text("")
                    ],
                  ),
                ),
          Text(
            title,
            style: TextStyle(fontSize: 24.s, color: Color(0xFF333333)),
          )
        ],
      ),
    );
  }

  Widget dengLu() {
    if (personalCenterResponse.memberInfo != null) {
      return Container(
          child: Stack(
        overflow: Overflow.visible,
        children: <Widget>[
          Container(
              child: ClipRRect(
                  borderRadius: BorderRadius.circular(10.0),
                  child: MyImage.network(personalCenterResponse.style.bgPath,
                      width: 700.w))),
          Positioned(
            left: 30.w,
            height: 200.h,
            width: 128.h,
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: <Widget>[
                Stack(
                  overflow: Overflow.visible,
                  children: <Widget>[
                    LoginIndex.getHeader(),
                    Positioned(
                      top: 135.s,
                      width: 128.h,
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.center,
                        children: <Widget>[
                          Container(
                            height: 32.h,
                            width: 80.w,
                            alignment: Alignment.center,
                            decoration: BoxDecoration(
                                color: Color(0xFFC9FFE1),
                                borderRadius: BorderRadius.circular(16.h)),
                            child: Text(
                              personalCenterResponse.memberInfo.isAutonym == 0
                                  ? "未实名"
                                  : "已实名",
                              style: TextStyle(
                                  color: Color(0xFF00C657), fontSize: 20.s),
                            ),
                          )
                        ],
                      ),
                    ),
                  ],
                ),
              ],
            ),
          ),
          Positioned(
              left: 220.w,
              top: 60.h,
              child: Row(
                children: <Widget>[
                  Text(
                    personalCenterResponse.memberInfo.nickname,
                    style: TextStyle(fontSize: 36.s, color: Colors.white),
                  ),
                  SizedBox(width: 20.w),
                  personalCenterResponse.vip.isVip == 0
                      ? Text("")
                      : Image.asset("images/user/ic_vip.png", height: 30.s)
                ],
              )),
          Positioned(
              left: 220.w,
              top: 110.h,
              child: Container(
                width: 400.w,
                child: Text(
                  personalCenterResponse.memberInfo.signature == ""
                      ? "你还没设置签名"
                      : personalCenterResponse.memberInfo.signature,
                  style: TextStyle(fontSize: 24.s, color: Colors.white),
                ),
              )),
          Positioned(
              top: 20.h,
              left: 610.w,
              child:
                  Image.asset("images/user/ic_mine_qiandao.png", height: 58.s)),
        ],
      ));
    }

    return Container(
        height: 200.h,
        child: Stack(
          children: <Widget>[
            Container(
                width: 710.w,
                child: ClipRRect(
                    borderRadius: BorderRadius.circular(10.0),
                    child:
                        MyImage.network(personalCenterResponse.style.bgPath))),
            Container(
              width: 710.w,
              child: Column(
                mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                children: <Widget>[
                  Text("嗨, 等您好久了!",
                      style: TextStyle(
                          fontSize: 36.s,
                          fontWeight: FontWeight.bold,
                          color: Colors.white)),
                  InkWell(
                    onTap: () {
                      LoginIndex.login();
                    },
                    child: Container(
                      height: 50.h,
                      width: 150.w,
                      alignment: Alignment.center,
                      decoration: BoxDecoration(
                          borderRadius: BorderRadius.circular(25.h),
                          border: Border.all(color: Colors.white, width: 1.w)),
                      child: Text(
                        "登录/注册",
                        style: TextStyle(
                          color: Colors.white,
                          fontSize: 28.s,
                        ),
                      ),
                    ),
                  )
                ],
              ),
            ),
          ],
        ));
  }

  Widget huiYuan() {
    return Row(
      mainAxisAlignment: MainAxisAlignment.center,
      children: <Widget>[
        Container(
          width: 630.w,
          height: 60.h,
          decoration: BoxDecoration(
              borderRadius: BorderRadius.only(
                  bottomLeft: Radius.circular(5),
                  bottomRight: Radius.circular(5)),
              image: DecorationImage(
                  fit: BoxFit.cover,
                  image: AssetImage("images/user/bg_member.png"))),
          child: Row(
            mainAxisAlignment: MainAxisAlignment.spaceAround,
            children: <Widget>[
              Text(
                " 赶马会员",
                style: TextStyle(fontSize: 28.s, color: Color(0xFFFFD5B1)),
              ),
              Text("|",
                  style: TextStyle(fontSize: 28.s, color: Color(0xFFFFD5B1))),
              Text(personalCenterResponse.vip.desc,
                  style: TextStyle(fontSize: 20.s, color: Color(0xFFFFD5B1))),
              Row(
                children: <Widget>[
                  Text("    查看详情",
                      style:
                          TextStyle(fontSize: 20.s, color: Color(0xFFFFD5B1))),
                  Icon(Icons.arrow_right, color: Color(0xFFFFD5B1))
                ],
              ),
            ],
          ),
        )
      ],
    );
  }

  // 小区店
  Widget _getStore() {
    if (personalCenterResponse.store == null) return Text("");
    return cardWidget(
        title: personalCenterResponse.store.type == 3 ? "我的小区" : "我的店铺",
        subtitle: "全部",
        imagePath: "images/user/ic_next.png",
        child: [
          Row(
              mainAxisAlignment: MainAxisAlignment.spaceAround,
              children: <Widget>[
                _getItem(personalCenterResponse.store.saleMoney, "本月销售"),
                _getItem(personalCenterResponse.store.balanceMoney, "余额",
                    tixian: "可提现"),
                _getItem(personalCenterResponse.store.waitMoney, "待结算金额"),
                _getItem(personalCenterResponse.store.withdrawMoney, "已提现"),
              ])
        ]);
  }

  _getItem(String money, String title, {String tixian}) {
    return Column(
      children: <Widget>[
        SizedBox(height: 10.h),
        Text.rich(TextSpan(children: [
          TextSpan(
              text: "￥",
              style: TextStyle(
                  color: Color(0xFFFF2B26),
                  fontSize: 20.s,
                  fontWeight: FontWeight.bold)),
          TextSpan(
              text: "$money",
              style: TextStyle(
                  fontSize: 28.s,
                  color: Color(0xFFFF2B26),
                  fontWeight: FontWeight.bold)),
        ])),
        SizedBox(height: 10.h),
        Text("$title", style: TextStyle(fontSize: 24.s)),
        tixian != null && money != "0"
            ? Container(
                margin: EdgeInsets.symmetric(vertical: 10.h),
                padding: EdgeInsets.symmetric(horizontal: 10.w),
                decoration: BoxDecoration(
                    borderRadius: BorderRadius.circular(20),
                    color: Colors.green),
                child: Text(
                  tixian ?? "",
                  style: TextStyle(fontSize: 20.s, color: Colors.white),
                ),
              )
            : Text("")
      ],
    );
  }

  //优惠券组件
  Widget _getYHQ() {
    if (personalCenterResponse.memberInfo == null) {
      return cardWidget(title: "我的优惠券", padding: 0, child: [
        Container(
          alignment: Alignment.center,
          height: 200.h,
          child: Text("您还未登录,登录注册领取超值优惠卷",
              style: TextStyle(fontSize: 24.s, color: "#FF999999".color)),
        )
      ]);
    }
    if (personalCenterResponse.couponInfo.personalCoupon.length == 0) {
      return cardWidget(title: "我的优惠券", child: [
        Container(
          width: 710.w,
          alignment: Alignment.center,
          height: 200.h,
          child: Text("暂无可领取的优惠券",
              style: TextStyle(fontSize: 24.s, color: "#FF999999".color)),
        )
      ]);
    }
    return cardWidget(
      title: "我的优惠券(${personalCenterResponse.couponInfo.totalNumber})",
      subtitle: "全部",
      imagePath: "images/user/ic_next.png",
      padding: 0,
      child: [
        Container(
            height: 160.h,
            child: ListView(
              scrollDirection: Axis.horizontal,
              children: personalCenterResponse.couponInfo.personalCoupon
                  .map((e) => Container(
                          child: Stack(
                        children: <Widget>[
                          e.memberCouponId == 0
                              ? Image.asset(
                                  "images/user/pic_mine_quanbg_get.png")
                              : Image.asset(
                                  "images/user/pic_mine_quanbg_use.png"),
                          Padding(
                            padding: EdgeInsets.symmetric(
                                vertical: 30.h, horizontal: 50.w),
                            child: Column(
                                mainAxisAlignment:
                                    MainAxisAlignment.spaceEvenly,
                                crossAxisAlignment: CrossAxisAlignment.start,
                                children: <Widget>[
                                  Row(
                                    children: <Widget>[
                                      Text("¥",
                                          style: TextStyle(
                                              color: Colors.red,
                                              fontSize: 24.s,
                                              fontWeight: FontWeight.bold)),
                                      Text(
                                          "${double.parse(e.fullMoney) % 1 == 0 ? double.parse(e.fullMoney).ceil() : double.parse(e.fullMoney)}",
                                          style: TextStyle(
                                              color: Colors.red,
                                              fontSize: 42.s,
                                              fontWeight: FontWeight.bold)),
                                    ],
                                  ),
                                  Text("${e.name}",
                                      style: TextStyle(
                                          color: Colors.red, fontSize: 24.s)),
                                  Text("${e.desc}",
                                      style: TextStyle(
                                          fontSize: 20.s,
                                          color: Color(0xFF333333)))
                                ]),
                          )
                        ],
                      )))
                  .toList(),
            ))
      ],
    );
  }

  @override
  void dispose() {
    super.dispose();
  }
}
